<script>
    import {Select} from 'view-design';
    import SelectHead from "./select/SelectHead";

    const getNestedProperty = (obj, path) => {
        const keys = path.split('.');
        return keys.reduce((o, key) => o && o[key] || null, obj);
    };

    const getOptionLabel = option => {
        if (option.componentOptions.propsData.label) return option.componentOptions.propsData.label;
        const textContent = (option.componentOptions.children || []).reduce((str, child) => str + (child.text || ''), '');
        const innerHTML = getNestedProperty(option, 'data.domProps.innerHTML');
        return textContent || (typeof innerHTML === 'string' ? innerHTML : '');
    };

    export default {
        extends: Select,

        registryName: 'Select',

        components: {SelectHead},

        name: Select.name,

        methods: {
            getOptionData(value){
                const option = this.flatOptions.find(({componentOptions}) => componentOptions.propsData.value === value);

                if (!option) {
                    if(this.allowCreate){
                        return {
                            value,
                            label: value,
                            disabled: false
                        };
                    }

                    return null;
                }

                const label = getOptionLabel(option);

                // 修复多选时，选项有disabled属性，选中项仍然能删除的 bug
                const disabled = option.componentOptions.propsData.disabled;

                return {
                    value: value,
                    label: label,
                    disabled: disabled
                };
            }
        }
    }
</script>